package com.joe.demo.chat.server;

import com.joe.demo.chat.protocol.MessageCodecSharable;
import com.joe.demo.chat.protocol.ProtocolFrameDecoder;
import com.joe.demo.chat.server.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-08-30
 */
@Slf4j
public class ChatServer {

    public static void main(String[] args) {
        final NioEventLoopGroup boss = new NioEventLoopGroup();
        final NioEventLoopGroup worker = new NioEventLoopGroup();
        final LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO);
        final MessageCodecSharable messageCodecSharable = new MessageCodecSharable();

        final LoginRequestMessageHandler loginRequestMessageHandler = new LoginRequestMessageHandler();
        final ChatRequestMessageHandler chatRequestMessageHandler = new ChatRequestMessageHandler();
        final GroupCreateRequestMessageHandler groupCreateRequestMessageHandler = new GroupCreateRequestMessageHandler();
        final GroupJoinRequestMessageHandler groupJoinRequestMessageHandler = new GroupJoinRequestMessageHandler();
        final GroupMembersRequestMessageHandler groupMembersRequestMessageHandler = new GroupMembersRequestMessageHandler();
        final GroupQuitRequestMessageHandler groupQuitRequestMessageHandler = new GroupQuitRequestMessageHandler();
        final GroupChatRequestMessageHandler groupChatRequestMessageHandler = new GroupChatRequestMessageHandler();
        final QuitHandler quitHandler = new QuitHandler();

        try {
            final ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            // 指定全连接队列大小
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            // 关闭 nagle 算法，及时发送消息，减少延迟
            serverBootstrap.childOption(ChannelOption.TCP_NODELAY, false);

            // serverBootstrap.option(); 是给 serverSocketChannel 配置参数
            // serverBootstrap.childOption(); 是给 SocketChannel 配置参数
            serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new ProtocolFrameDecoder());
                    channel.pipeline().addLast(loggingHandler);
                    channel.pipeline().addLast(messageCodecSharable);

                    // 用来判断，读空闲时间、写空闲时间是不是过长
                    // 5s 内没有收到 channel 的数据，会触发一个事件 IdleState#READER_IDLE 事件
                    channel.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                    // ChannelDuplexHandler 可同时作为出站和入站事件
                    channel.pipeline().addLast(new ChannelDuplexHandler(){
                        /**
                         * 用来触发特殊事件
                         * @param ctx
                         * @param evt
                         * @throws Exception
                         */
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            final IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发读空闲事件
                            if (event.state() == IdleState.READER_IDLE){
                                log.info("已经 5s 没读到数据了");
                                ctx.channel().close();
                            }
                        }
                    });

                    channel.pipeline().addLast(loginRequestMessageHandler);
                    channel.pipeline().addLast(chatRequestMessageHandler);
                    channel.pipeline().addLast(groupCreateRequestMessageHandler);
                    channel.pipeline().addLast(groupJoinRequestMessageHandler);
                    channel.pipeline().addLast(groupMembersRequestMessageHandler);
                    channel.pipeline().addLast(groupQuitRequestMessageHandler);
                    channel.pipeline().addLast(groupChatRequestMessageHandler);
                    channel.pipeline().addLast(quitHandler);
                }
            });
            final ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (InterruptedException exception){
            exception.printStackTrace();
            log.error("server error: ", exception);
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
